package ch.epfl.lara.core.parser

import scala.util.parsing.combinator._

import ch.epfl.lara.core.ast._

object Parser extends Parsers {
  delimiters.incl('(', ')', '{', '}', '[', ']', ':', '.', '=')
  keywords.incl("object", "unapply", "class", "/*", "*/", "invariants", "def", "preconditions", "postconditions", "match", "case", "if", "else", "extends", "new", "!=", "==", "<", "<=", ">", ">=", "&&", "||")

  /**
   *  Term	::=	Ident
   */
  def Term: Parser = production(
      ident
    | failure("illegal start of term"))

  override def build(xs: List[Token], pos: Position): AST = xs match {
    case Identifier(ident) :: Nil => Ident(ident)
  }

  def parse(in: String): Option[AST] = {
    val res = run(AST, in)
    res match {
      case Success(_, _) => output(res)
      case Failure(_, _) => println(res); None
    }
  }

  def parseFile(fileName: String): Option[AST] = try {
    val buffer = new compat.StringBuilder
    io.Source.fromFile(fileName) foreach (line => buffer.append(line))
    parse(buffer.toString)
  } catch {
    case e: java.io.FileNotFoundException => println(e.getMessage)
    None
  }
}
